<?php

namespace app\admin\service;

use app\common\model\Config;
use app\common\model\ConfigData;

/**
 * 系统配置-服务类
 * @author 小码哥
 * @since 2023/3/28
 * Class ConfigWebService
 * @package app\admin\service
 */
class ConfigWebService extends BaseService
{
    /**
     * 构造函数
     * @author 小码哥
     * @since 2023/3/28
     * ConfigWebService constructor.
     */
    public function __construct()
    {
        $this->model = new Config();
    }

    /**
     * 获取配置数据列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 小码哥
     * @since 2023/3/28
     */
    public function getList()
    {
        // 获取配置列表
        $configList = $this->model
            ->where("mark", "=", 1)
            ->order("sort asc")
            ->select()
            ->toArray();
        $list = [];
        if ($configList) {
            $configDataModel = new ConfigData();
            foreach ($configList as &$val) {
                $dataList = $configDataModel
                    ->where("config_id", "=", $val['id'])
                    ->where("mark", "=", 1)
                    ->order("sort asc")
                    ->select()
                    ->toArray();
                foreach ($dataList as &$v) {
                    switch ($v['type']) {
                        case 'array':
                        case 'radio':
                        case 'checkbox':
                        case 'select':
                            $data = preg_split('/[\r\n]+/s', $v['options']);
                            if ($data) {
                                $arr = [];
                                foreach ($data as $vt) {
                                    $value = preg_split('/[:：]+/s', $vt);
                                    $arr[$value[0]] = $value[1];
                                }
                                $v['param'] = $arr;
                            }
                            // 复选框
                            if ($v['type'] == "checkbox") {
                                $v['value'] = explode(",", $v['value']);
                            }
                            break;
                        case 'image':
                            if (!empty($v['value'])) {
                                $v['value'] = get_image_url($v['value']);
                            }
                            break;
                        case 'images':
                            $urlList = explode(",", $v['value']);
                            $itemList = [];
                            foreach ($urlList as $vt) {
                                if (empty($vt)) {
                                    continue;
                                }
                                $itemList[] = get_image_url($vt);
                            }
                            $v['value'] = $itemList;
                            break;
                    }
                }
                $item = array();
                $item['config_id'] = $val['id'];
                $item['config_name'] = $val['name'];
                $item['item_list'] = $dataList;
                $list[] = $item;
            }
        }
        return message("操作成功", true, $list);
    }

    /**
     * 保存表单信息
     * @return array
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @since 2023/3/28
     * @author 小码哥
     */
    public function edit()
    {
        // 参数
        $data = request()->param();
        if (!$data) {
            return message("参数不能为空", false);
        }
        $configId = $data['config_id'];
        unset($data['config_id']);
        $configDataModel = new ConfigData();
        foreach ($data as $key => &$val) {
            // 图片处理
            $preg = "/^http(s)?:\\/\\/.+/";
            if (is_string($val) && preg_match($preg, $val)) {
                if (strpos($val, "temp") !== false) {
                    $val = save_image($val, 'config');
                } else {
                    $val = str_replace(IMG_URL, "", $val);
                }
            }
            if (is_array($val)) {
                $item = [];
                foreach ($val as $vt) {
                    $preg = "/^http(s)?:\\/\\/.+/";
                    if (preg_match($preg, $vt)) {
                        if (strpos($vt, "temp") !== false) {
                            $vt = save_image($vt, 'config');
                        } else {
                            $vt = str_replace(IMG_URL, "", $vt);
                        }
                        $item[] = $vt;
                    } else {
                        $item[] = $vt;
                    }
                }
                $val = !empty($item) ? implode(",", $item) : "";
            }
            $result = $configDataModel
                ->where("code", "=", $key)
                ->where("config_id", "=", $configId)
                ->field('id')
                ->find();
            $info = [];
            $info['id'] = $result['id'];
            $info['value'] = !empty($val) ? $val : "";
            $configDataModel->edit($info);
        }
        $this->saveWxPaySet($data);
        return message('操作成功');
    }

    /**
     * @param $data
     * @return bool
     * 保存微信支付证书
     * $dir = DATA_PATH . 'cert';
     */
    private function saveWxPaySet($data)
    {
        // 创建目录
        $dir = DATA_PATH . 'cert';
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        // 检查并保存apiclient_cert
        if (isset($data['apiclient_cert_pem']) && !empty($data['apiclient_cert_pem'])) {
            $apiclient_cert = trim($data['apiclient_cert_pem']);
            $filename = $dir . '/apiclient_cert.pem';
            $ret = file_put_contents($filename, $apiclient_cert);
            if ($ret === false) {
                return false;
            }
        }
        // 检查并保存apiclient_key
        if (isset($data['apiclient_key_pem']) && !empty($data['apiclient_key_pem'])) {
            $apiclient_key = trim($data['apiclient_key_pem']);
            $filename = $dir . '/apiclient_key.pem';
            $ret = file_put_contents($filename, $apiclient_key);
            if ($ret === false) {
                return false;
            }
        }
        return true; // 如果所有保存操作都成功，返回true
    }

    /**
     * @param $data
     * @throws \think\db\exception\BindParamException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更新信息
     */
    public function upConfig($data)
    {
        $configId = $data['config_id'];
        unset($data['config_id']);
        foreach ($data as $key => &$val) {
            // 图片处理
            $preg = "/^http(s)?:\\/\\/.+/";
            if (is_string($val) && preg_match($preg, $val)) {
                if (strpos($val, "temp") !== false) {
                    $val = save_image($val, 'config');
                } else {
                    $val = str_replace(IMG_URL, "", $val);
                }
            }
            if (is_array($val)) {
                $item = [];
                foreach ($val as $vt) {
                    $preg = "/^http(s)?:\\/\\/.+/";
                    if (preg_match($preg, $vt)) {
                        if (strpos($vt, "temp") !== false) {
                            $vt = save_image($vt, 'config');
                        } else {
                            $vt = str_replace(IMG_URL, "", $vt);
                        }
                        $item[] = $vt;
                    } else {
                        $item[] = $vt;
                    }
                }
                $val = !empty($item) ? implode(",", $item) : "";
            }
            $configDataModel = new ConfigData();
            $result = $configDataModel
                ->where("code", "=", $key)
                ->where("config_id", "=", $configId)
                ->find();
            $info = [];
            $info['id'] = $result['id'];
            $info['value'] = !empty($val) ? $val : "";
            $configDataModel->edit($info);
        }
    }
}